<template>
  <el-dialog
    :append-to-body="true"
    :close-on-click-modal="false"
    :lock-scroll="true"
    :title="title"
    top="5vh"
    :visible.sync="dialogFormVisible"
    width="666px"
    @close="close"
  >
    <div class="resident-modal">
      <el-collapse v-model="collapseList">
        <el-collapse-item name="1" title="居民基本信息">
          <el-form
            ref="form"
            :label-position="'right'"
            label-width="auto"
            :model="form"
            :rules="rules"
          >
            <el-form-item label="居民姓名">
              <span>{{ form.name }}</span>
            </el-form-item>
            <el-form-item label="性别">
              <span>{{ sexType[form.sex] || '-' }}</span>
            </el-form-item>
            <el-form-item label="人员类型">
              <span>{{ userType[form.type] || '-' }}</span>
            </el-form-item>
            <el-form-item label="授权类型">
              <span>{{ authType[form.authType] || '-' }}</span>
            </el-form-item>
            <el-form-item label="居民照片">
              <img
                v-if="form.photo"
                alt=""
                class="avatar"
                :src="prevUrl + form.photo"
              />
            </el-form-item>
            <el-form-item label="出生日期">
              <span>{{ form.birthday }}</span>
            </el-form-item>
            <el-form-item label="国籍">
              <span>{{ countryList[form.nationCode] || '-' }}</span>
            </el-form-item>
            <el-form-item label="民族">
              <span>{{ form.nation || '-' }}</span>
            </el-form-item>
            <el-form-item label="证件类型">
              <span>{{ certType[form.certType] || '-' }}</span>
            </el-form-item>
            <el-form-item label="证件号码">
              <span>{{ form.certNo }}</span>
            </el-form-item>
            <el-form-item label="手机号码">
              <span>{{ form.phone }}</span>
            </el-form-item>
            <el-form-item label="户籍所在地址">
              <span>{{ form.address || '-' }}</span>
            </el-form-item>
            <el-form-item label="现居住地址">
              <span>{{ form.liveAddress || '-' }}</span>
            </el-form-item>
            <el-form-item label="街镇编码">
              <span>{{ form.townNo }}</span>
            </el-form-item>
            <el-form-item label="小区编码">
              <span>{{ form.areaNo }}</span>
            </el-form-item>
            <el-form-item label="授权开始时间">
              <span>{{ form.authStartDate }}</span>
            </el-form-item>
            <el-form-item label="授权结束时间">
              <span>{{ form.authEndDate }}</span>
            </el-form-item>
          </el-form>
        </el-collapse-item>
        <el-collapse-item v-if="hasHouse" name="2" title="房屋信息">
          <el-form
            ref="houseForm"
            :label-position="'right'"
            label-width="auto"
            :model="houseForm"
            :rules="houseRules"
          >
            <el-form-item label="房屋地址">
              <span>{{ houseForm.address }}</span>
            </el-form-item>
            <el-form-item label="小区名称">
              <span>{{ houseForm.areaName }}</span>
            </el-form-item>
            <el-form-item label="楼牌号">
              <span>{{ houseForm.builderName }}</span>
            </el-form-item>
            <el-form-item label="单元">
              <span>{{ houseForm.unitName }}</span>
            </el-form-item>
            <el-form-item label="房间号">
              <span>{{ houseForm.roomName }}</span>
            </el-form-item>
            <el-form-item label="户型室">
              <span>{{ houseForm.shiNum }}</span>
            </el-form-item>
            <el-form-item label="户型厅">
              <span>{{ houseForm.tingNum }}</span>
            </el-form-item>
            <el-form-item label="户型厨">
              <span>{{ houseForm.chuNum }}</span>
            </el-form-item>
            <el-form-item label="户型卫">
              <span>{{ houseForm.weiNum }}</span>
            </el-form-item>
            <el-form-item label="户型阳台">
              <span>{{ houseForm.balconyNum }}</span>
            </el-form-item>
            <el-form-item label="房屋建筑面积">
              <span>{{ houseForm.buildArea }}</span>
            </el-form-item>
            <el-form-item label="房屋使用面积">
              <span>{{ houseForm.useArea }}</span>
            </el-form-item>
          </el-form>
        </el-collapse-item>
      </el-collapse>
    </div>
    <template #footer>
      <el-button @click="close">关 闭</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import {
    getTownList,
    getAreaList,
    getBuilderList,
    getRoomList,
    getNorthUserById,
    uploadUrl,
  } from '@/api/resident'
  import { mapGetters } from 'vuex'
  import { picBaseUrl, baseURL } from '@/config'

  // 转换树状列表
  function transTree(list) {
    const reCall = (item) => {
      item.value = item.id + ':' + item.name
      item.label = item.name
      if (Array.isArray(item.children) && item.children.length > 0) {
        item.children.forEach((v) => {
          reCall(v)
        })
      }
    }
    list.forEach((v) => {
      reCall(v)
    })
  }

  export default {
    name: 'NorthResident',
    data() {
      const photoCheck = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请上传照片'))
        } else {
          callback()
        }
      }
      return {
        hasHouse: false,
        userType: {
          1: '业主',
          2: '租户',
          3: '其他',
          4: '工作人员',
          5: '访客',
        },
        authType: {
          1: '有效',
          2: '永久',
        },
        collapseList: ['1', '2', '3'],
        imageUrl: '',
        upToServerUrl: baseURL + uploadUrl,
        prevUrl: '',
        isSaving: false,
        form: {
          address: null,
          areaNo: null,
          birthday: null,
          certNo: null,
          certType: null,
          city: null,
          cityCode: null,
          county: null,
          countyCode: null,
          liveAddress: null,
          name: null,
          nation: null,
          nationCode: null,
          phone: null,
          photo: null,
          politicalClimate: null,
          province: null,
          provinceCode: null,
          roomId: null,
          sex: null,
          townNo: null,
          provinceCityList: [],
          education: null,
          hasLivePermit: null,
          isBuyCar: null,
          isElecCar: null,
          isGrid: null,
          isPet: null,
          isSoldier: null,
          isVolunteer: null,
          joinPartyDate: null,
          maritalStatus: null,
          outDate: null,
          outReason: null,
          partyRelation: null,
          workStatus: null,
          workCompany: null,
          authStartDate: null,
          authEndDate: null,
          type: null,
          authType: null,
        },
        houseForm: {
          address: null,
          areaName: null,
          builderName: null,
          unitName: null,
          roomName: null,
          shiNum: null,
          tingNum: null,
          chuNum: null,
          weiNum: null,
          balconyNum: null,
          buildArea: null,
          useArea: null,
        },
        carForm: {
          areaNo: null,
          brand: null,
          carColor: null,
          carType: null,
          parkType: null,
          plateColor: null,
          plateNo: null,
          townNo: null,
          useAddress: null,
          useCertNo: null,
          useCertType: null,
          useName: null,
        },
        rules: {
          certType: [
            { required: true, trigger: 'change', message: '请输入证件类型' },
          ],
          certNo: [
            { required: true, trigger: 'blur', message: '请输入证件号码' },
          ],
          photo: [{ required: true, validator: photoCheck, trigger: 'blur' }],
          name: [{ required: true, trigger: 'blur', message: '请输入姓名' }],
          phone: [
            { required: true, trigger: 'blur', message: '请输入手机号码' },
          ],
          birthday: [
            { required: true, trigger: 'blur', message: '请选择生日' },
          ],
          sex: [{ required: true, trigger: 'change', message: '请选择性别' }],
          nationCode: [
            { required: true, trigger: 'change', message: '请选择国籍' },
          ],
          nation: [
            { required: true, trigger: 'change', message: '请选择民族' },
          ],
          politicalClimate: [
            { required: true, trigger: 'change', message: '请选择政治面貌' },
          ],
          liveAddress: [
            { required: true, trigger: 'blur', message: '请输入居住地址' },
          ],
          provinceCityList: [
            { required: true, trigger: 'change', message: '请选择省市区' },
          ],
          address: [
            { required: true, trigger: 'blur', message: '请选择详细地址' },
          ],
        },
        houseRules: {
          townNo: [
            { required: true, trigger: 'change', message: '请选择街道' },
          ],
          areaNo: [
            { required: true, trigger: 'change', message: '请选择小区' },
          ],
          builderId: [
            { required: true, trigger: 'change', message: '请选择楼牌号' },
          ],
          roomList: [
            { required: true, trigger: 'change', message: '请选择房间号' },
          ],
          roomNum: [
            { required: true, trigger: 'change', message: '请选择户型' },
          ],
          linkName: [
            {
              required: true,
              trigger: 'blur',
              message: '请选择房屋联系人姓名',
            },
          ],
          linkPhone: [
            {
              required: true,
              trigger: 'blur',
              message: '请选择房屋联系人手机号',
            },
          ],
          linkCertType: [
            {
              required: true,
              trigger: 'change',
              message: '请选择房屋联系人证件类型',
            },
          ],
          linkCertNo: [
            {
              required: true,
              trigger: 'blur',
              message: '请选择房屋联系人证件号码',
            },
          ],
        },
        carRules: {},
        title: '',
        dialogFormVisible: false,
        townList: [],
        areaList: [],
        builderList: [],
        roomList: [],
        currentTownId: null,
      }
    },
    computed: {
      ...mapGetters({
        treeList: 'user/treeList',
        certType: 'dict/certTypeJson',
        carColor: 'dict/carColor',
        carBrand: 'dict/carBrand',
        carType: 'dict/carType',
        countryList: 'dict/countryListJson',
        sexType: 'dict/sexTypeJson',
        nationList: 'dict/nationListJson',
        policyRole: 'dict/policyRole',
        roomType: 'dict/roomType',
        plateColor: 'dict/plateColor',
      }),
    },
    mounted() {},
    methods: {
      clearCarRule() {
        this.carRules = {}
        if (this.$refs['carForm']) {
          this.$refs['carForm'].clearValidate()
        }
      },
      checkCarRules() {
        let isEmpty = true
        for (let key in this.carForm) {
          if (this.carForm[key]) {
            isEmpty = false
            break
          }
        }
        if (isEmpty) {
          this.clearCarRule()
        } else {
          this.carRules = {
            plateNo: [
              { required: true, trigger: 'blur', message: '请输入车牌号' },
            ],
            plateColor: [
              { required: true, trigger: 'change', message: '请选择车牌颜色' },
            ],
            brand: [
              { required: true, trigger: 'change', message: '请选择车辆品牌' },
            ],
            carType: [
              { required: true, trigger: 'change', message: '请选择车辆类型' },
            ],
            carColor: [
              { required: true, trigger: 'change', message: '请选择车辆颜色' },
            ],
            useName: [
              {
                required: true,
                trigger: 'blur',
                message: '请输入车辆使用人姓名',
              },
            ],
            useCertNo: [
              {
                required: true,
                trigger: 'blur',
                message: '请输入车辆使用人证件号码',
              },
            ],
            useAddress: [
              {
                required: true,
                trigger: 'blur',
                message: '请输入车辆使用人居住地址',
              },
            ],
            useCertType: [
              {
                required: true,
                trigger: 'change',
                message: '请选择车辆使用人证件类型',
              },
            ],
          }
        }
      },
      _getTownList() {
        getTownList()
          .then((res) => {
            if (res.status === 0 && Array.isArray(res.data)) {
              this.townList = res.data
            }
          })
          .catch((e) => {
            console.log(e)
          })
      },
      _getAreaList(townId) {
        if (townId === undefined || townId === null || townId === '') {
          return
        }
        getAreaList(townId)
          .then((res) => {
            if (res.status === 0 && Array.isArray(res.data)) {
              this.areaList = res.data
              if (this.currentTownId) {
                for (let i = 0; i < res.data.length; i++) {
                  if (res.data[i].code === this.houseForm.areaNo) {
                    this._getBuilderList(res.data[i].id)
                    break
                  }
                }
              }
            }
          })
          .catch((e) => {
            console.log(e)
          })
      },
      _getBuilderList(areaId) {
        getBuilderList(areaId)
          .then((res) => {
            if (res.status === 0 && Array.isArray(res.data)) {
              this.builderList = res.data
              if (this.currentTownId) {
                for (let i = 0; i < res.data.length; i++) {
                  if (res.data[i].id === this.houseForm.builderId) {
                    this._getRoomList(res.data[i].id)
                    break
                  }
                }
              }
            }
          })
          .catch((e) => {
            console.log(e)
          })
      },
      _getRoomList(builderId) {
        getRoomList(builderId)
          .then((res) => {
            if (res.status === 0 && Array.isArray(res.data)) {
              transTree(res.data)
              this.roomList = res.data
              // if (this.currentTownId) {
              //   this.$set(this.houseForm, 'roomList', [
              //     ...this.houseForm.roomList,
              //   ])
              // }
            }
          })
          .catch((e) => {
            console.log(e)
          })
      },
      changeTown(code) {
        let id = ''
        for (let i = 0; i < this.townList.length; i++) {
          if (this.townList[i].code === code) {
            id = this.townList[i].id
            break
          }
        }
        // console.log('changTown', id)
        this.form.area = ''
        this.form.builder = ''
        this.form.room = ''
        this.areaList = []
        this.builderList = []
        this.roomList = []
        this._getAreaList(id)
      },
      changeArea(code) {
        let id = ''
        for (let i = 0; i < this.areaList.length; i++) {
          if (this.areaList[i].code === code) {
            id = this.areaList[i].id
            break
          }
        }
        // console.log('changeArea', id)
        this.form.builder = ''
        this.form.room = ''
        this.builderList = []
        this.roomList = []
        this._getBuilderList(id)
      },
      changeBuilder(id) {
        // console.log('changeBuilder', id)
        this.form.room = ''
        this.roomList = []
        this._getRoomList(id)
      },
      handleEditForm(row) {
        const resident = row
        this.form = {
          address: resident.address || null,
          areaNo: resident.areaNo || null,
          birthday: resident.birthday || null,
          certNo: resident.certNo || null,
          certType: resident.certType || null,
          city: resident.city || null,
          cityCode: resident.cityCode || null,
          county: resident.county || null,
          countyCode: resident.countyCode || null,
          liveAddress: resident.liveAddress || null,
          name: resident.name || null,
          nation: +resident.nation + '' || null,
          nationCode: resident.nationCode || null,
          phone: resident.phone || null,
          photo: resident.photo ? picBaseUrl + resident.photo : null,
          politicalClimate: resident.politicalClimate || null,
          province: resident.province || null,
          provinceCode: resident.provinceCode || null,
          roomId: resident.roomId || null,
          sex: resident.sex || null,
          townNo: resident.townNo || null,
          education: resident.education || null,
          hasLivePermit: resident.hasLivePermit || null,
          isBuyCar: resident.isBuyCar || null,
          isElecCar: resident.isElecCar || null,
          isGrid: resident.isGrid || null,
          isPet: resident.isPet || null,
          isSoldier: resident.isSoldier || null,
          isVolunteer: resident.isVolunteer || null,
          joinPartyDate: resident.joinPartyDate || null,
          maritalStatus: resident.maritalStatus || null,
          outDate: resident.outDate || null,
          outReason: resident.outReason || null,
          partyRelation: resident.partyRelation || null,
          workStatus: resident.workStatus || null,
          workCompany: resident.workCompany || null,
          authStartDate: resident.authStartDate || null,
          authEndDate: resident.authEndDate || null,
          type: resident.type || null,
          authType: resident.authType || null,
        }
      },
      showEdit(rowBase) {
        console.log(rowBase)
        this.title = '查看居民信息'
        if (rowBase) {
          this.handleEditForm(rowBase)
          this.hasHouse = false
          getNorthUserById(rowBase.id)
            .then((res) => {
              if (res && res.data && res.data.house) {
                this.hasHouse = true
                // this.handleEditForm(res.data)
                const house = res.data.house
                // this.houseForm = {
                this.houseForm.address = house.address || '-'
                this.houseForm.areaName = house.areaName || '-'
                this.houseForm.builderName = house.builderName || '-'
                this.houseForm.unitName = house.unitName || '-'
                this.houseForm.roomName = house.roomName || '-'
                this.houseForm.shiNum = house.shiNum || '-'
                this.houseForm.tingNum = house.tingNum || '-'
                this.houseForm.chuNum = house.chuNum || '-'
                this.houseForm.weiNum = house.weiNum || '-'
                this.houseForm.balconyNum = house.balconyNum || '-'
                this.houseForm.buildArea = house.buildArea || '-'
                this.houseForm.useArea = house.useArea || '-'
                // };
              }
            })
            .catch((err) => {
              console.log(err)
            })
        }
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.$refs['houseForm'].resetFields()
        // this.$refs['carForm'].resetFields()
        this.form = this.$options.data().form
        this.houseForm = this.$options.data().houseForm
        // this.carForm = this.$options.data().carForm
        this.dialogFormVisible = false
        this.currentTownId = null
        this.clearCarRule()
      },
      handleAvatarSuccess(res) {
        if (res && res.status === 0 && res.data) {
          // this.imageUrl = URL.createObjectURL(file.raw)
          this.form.photo = picBaseUrl + res.data
          this.$refs.form.validateField('photo')
        } else {
          this.$message.error('图片上传失败，请重试!')
          this.form.photo = ''
          this.$refs.form.validateField('photo')
        }
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG、PNG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!')
        }
        return isJPG && isLt2M
      },
    },
  }
</script>
<style lang="scss">
  $picWH: 32px;
  $picFont: 14px;
  .resident-modal {
    height: calc(100vh - 250px);
    overflow: auto;
    padding: 0 10px 0 0;
    //width: 666px;
    //margin: 0 auto;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: $picFont;
    color: #8c939d;
    width: $picWH;
    height: $picWH;
    line-height: $picWH;
    text-align: center;
  }
  .avatar {
    width: $picWH;
    height: $picWH;
    display: block;
  }
  .full-select {
    width: 100%;
  }
</style>
